package top.melody.ecommerce.webapps.console.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.melody.ecommerce.common.util.HTTPUtil;
import top.melody.ecommerce.common.util.JsonMapper;
import top.melody.ecommerce.platform.handler.enums.ResultMsg;
import top.melody.ecommerce.webapps.console.base.AssertContext;
import top.melody.ecommerce.webapps.console.base.SecurityUserSession;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        SecurityUserSession session = AssertContext.getCurrentSecurityUser(request);
        if(session == null) {
            if(HTTPUtil.isJsonRequest(request)) {
                //ajax请求，如果session过期，手动在页面上跳到登录页面
                ResultMsg resultMsg = new ResultMsg(ResultMsg.CODE_NOT_LOGIN, "user login expired");
                HTTPUtil.writeJson(response, JsonMapper.nonEmptyMapper().toJson(resultMsg));
            } else
                response.sendRedirect(AssertContext.getContextPath(request) + "/login");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
